const jwt = require('jsonwebtoken')
const { PUBLIC_KEY } = require('../app/config')

const errorTypes = require('../constants/errot-type')
const userService = require('../service/user.service')
const authService = require('../service/auth.service')
const md5password = require('../utils/password-handle')
const verifyLogin = async (ctx, next) => {

    const { username, password } = ctx.request.body
    console.log('username, password ',username, password )
    // 1.判断用户名和密码是否为空
    if(!username || !password) {
        const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED)
        return ctx.app.emit('error', error, ctx)
    }

    // 2.判断用户是否存在
    const result = await userService.getUserByName(username)
    console.log('result',result)
    const user = result[0]
    if(!user) {
        const error = new Error(errorTypes.USER_DOSE_NOT_EXISTS)
        return ctx.app.emit('error', error, ctx)
    }

    // 3.判断密码是否正确
    if(md5password(password) != user.password) {
        const error = new Error(errorTypes.PASSWORD_IS_INCORRNCT)
        return ctx.app.emit('error', error, ctx)
    }

    ctx.user = user

    await next()
}

const verifyAuth = async (ctx, next) => {
    console.log('验证授权',ctx)

    // 获取token
    if(!ctx.headers.authorization) {

        const err = new Error(errorTypes.UNAUTHORIZATION)
        return ctx.app.emit('error', err, ctx)
    }
    const authorization = ctx.headers.authorization
    const token = authorization.replace('Bearer ', '')
    // 验证token

    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithms: ['RS256']
        })
        ctx.user = result
        await next()
    } catch (error) {   
        const err = new Error(errorTypes.UNAUTHORIZATION)
        return ctx.app.emit('error', err)   
    }
}

const verifyPermission = async (ctx, next) => {
    console.log('验证权限~')
    try {
        
    } catch (error) {
        
    }
    const  tableId = Object.values(ctx.params)[0]
    const resourceName = Object.keys(ctx.params)[0].replace('Id', '')
    console.log(tableId,resourceName,'resourceName')
    const { id } = ctx.user
    // const { momentId } = ctx.params

    try {
        const isPermission = await authService.checkResource(resourceName, tableId, id)
        console.log('isPermission',isPermission)
        if(!isPermission) throw new Error()
        await next()
    } catch (err) {
        const error = new Error(errorTypes.UNPERMISSION)
        ctx.app.emit('error', error, ctx)
    }
}

module.exports = {
    verifyLogin,
    verifyAuth,
    verifyPermission
}
